﻿using System;
using System.Windows.Input;
using BHS.TFSChangsetAnalyser.Export;

namespace BHS.TFSChangsetAnalyser.ViewModel
{
    public class ExportCommand : ICommand
    {
        private readonly IMainWindowViewModel _viewModel;
        private readonly IExportFilenameProvider _filenameProvider;
        private readonly IChangesetInfoExporter _exporter;

        public ExportCommand(IMainWindowViewModel viewModel, IExportFilenameProvider filenameProvider, IChangesetInfoExporter exporter)
        {
            _viewModel = viewModel;
            _filenameProvider = filenameProvider;
            _exporter = exporter;
        }

        public void Execute(object parameter)
        {
            string filename = _filenameProvider.GetExportFilename();
            if (!string.IsNullOrEmpty(filename))
            {
                try
                {
                    _viewModel.IsBusy = true;

                    _exporter.ExportDataToFile(filename, _viewModel.AnalysisResults.ChangesetInfos);
                }
                finally
                {
                    _viewModel.IsBusy = false;
                }                
            }
        }

        public bool CanExecute(object parameter)
        {
            return _viewModel.AnalysisResults.HasResults;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}
